import base64
import os
from flask import Flask, request, jsonify
from services.wordcloud.chnSegment import get_word_freq
from services.wordcloud.plotWordcloud import generate_wordcloud_from_frequencies

app = Flask(__name__)

@app.route("/wordcloud", methods=["POST"])
def wordcloud_api():
    data = request.get_json()
    text = data.get("text", "")
    colormap = data.get("colormap", "viridis")
    min_freq = data.get("min_freq", 2)

    if not text:
        return jsonify({"error": "缺少参数 text"}), 400

    try:
        word_freq = get_word_freq(text, min_freq=min_freq)
        output_path = generate_wordcloud_from_frequencies(
            word_freq,
            colormap=colormap
        )
        
        with open(output_path, "rb") as f:
            img_base64 = base64.b64encode(f.read()).decode("utf-8")

        return jsonify({"status": "ok", "base64": img_base64})
    except ValueError as e:
        return jsonify({"error": str(e)}), 400
    except Exception as e:
        return jsonify({"error": f"生成词云时出错: {str(e)}"}), 500

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5200))
    app.run(host="0.0.0.0", port=port)